<template>
  <div>
    <form-dialog
        ref="formDialogRef"
        :form-props="formProps"
        :height="69"
        @save="generateBtnRule"
        label-width="6rem"
        @reset="resetForm"
    >
      <template #rulePrefix="scope">
        <div style="width: 50%;display: flex;justify-content: space-between">
          <el-input style="width: 45%" v-model="scope.row.rulePrefix[0]"/>
          <span style="font-size: 1.5rem;font-weight: bolder">:</span>
          <el-input style="width: 45%" v-model="scope.row.rulePrefix[1]"/>
        </div>
      </template>

      <template #rules="scope">
        <el-checkbox :indeterminate="checked.isIndeterminate" v-model="checked.checkAll" @change="(e) => handleCheckAllChange(e, scope.row)">全选</el-checkbox>
        <div style="margin: 15px 0;"/>
        <el-checkbox-group v-model="scope.row.rules" @change="handleCheckedBtnChange">
          <el-checkbox v-for="rule in allRules" :value="rule" :key="rule.rule">
            <span>{{ fatherData.menuName }}-</span>
            <span style="color: #1890ff;font-weight: bold;">{{ rule.label }}</span>
          </el-checkbox>
        </el-checkbox-group>
      </template>


      <template #customRules="scope">
        <div style="width: 100%;display: flex;justify-content: space-between;">
          <el-input
              style="width: 40%"
              ref="customRulesLabel"
              v-model="customRules.label"
              @keyup.enter="handleAddCustomRule(scope.row,true)"
          >
            <template #prepend>{{ scope.row.labelPrefix }}</template>
          </el-input>
          <el-input
              style="width: 30%"
              ref="customRulesRule"
              v-model="customRules.rule"
              @keyup.enter="handleAddCustomRule(scope.row,true)"
          >
            <template #prepend>权限字符</template>
          </el-input>
          <div style="width: 15%">
            <div v-show="customRules.label && customRules.rule">
              <el-button
                  style="margin-right: 1rem"
                  type="primary"
                  circle
                  icon="el-icon-check"
                  @click="handleAddCustomRule(scope.row)"
              />
              <el-button
                  type="danger"
                  circle
                  icon="el-icon-delete"
                  @click="handleRest"
              />
            </div>
          </div>
        </div>
      </template>


      <template #customRulesTable="scope">
        <el-table
            border
            height="33vh"
            :data="scope.row.customRules"
        >
          <el-table-column label="权限名称" prop="label" align="center"/>
          <el-table-column label="权限字符" prop="rule" align="center"/>
          <el-table-column label="操作" width="100px" align="center">
            <template #default="rule">
              <el-button
                  type="danger"
                  circle
                  icon="el-icon-delete"
                  @click="scope.row.customRules.splice(rule.$index, 1)"
              />
            </template>
          </el-table-column>
        </el-table>
      </template>
    </form-dialog>
  </div>
</template>

<script setup>
const formDialogRef = useTemplateRef('formDialogRef')
const customRulesLabel = ref(null)
const customRulesRule = ref(null)
const fatherData = ref({})

const allRules = [
  {rule: 'query', label: '查询'},
  {rule: 'add', label: '新增'},
  {rule: 'edit', label: '编辑'},
  {rule: 'delete', label: '删除'},
  {rule: 'status', label: '状态修改'},
]
const checked = reactive({
  isIndeterminate: false,
  checkAll: false,
})

const customRules = reactive({
  label: '',
  rule: '',
})

const checkPrefix = (form) => {
  return (rule, value, callback) => {
    if (value.length === 2 && value[0] !== '' && value[1] !== '') callback()
    else callback(new Error('权限前缀未填写完整'))
  }
}

const formProps = computed(() => ([
  {label: '名称前缀', prop: 'labelPrefix', type: $formType.input()},
  {label: '权限前缀', prop: 'rulePrefix', type: $formType.slot(), default: [], rule: $formVerify.useFunc(checkPrefix)},
  {label: '按钮选择', prop: 'rules', type: $formType.slot(), default: [], required: false},
  {label: '自定义按钮', prop: 'customRules', type: $formType.slot(), required: false, default: []},
  {slot: "customRulesTable"},
]))

const handleCheckedBtnChange = (event) => {
  const checkedCount = event.length
  const allLength = allRules.length
  checked.checkAll = checkedCount === allLength
  checked.isIndeterminate = checkedCount > 0 && checkedCount < allLength
}

const handleCheckAllChange = (event, form) => {
  form.rules = event ? [...allRules] : []
  checked.isIndeterminate = false
}

const handleAddCustomRule = (form, isEnter) => {
  if (!isEnter && (!customRules.label || !customRules.rule)) return
  if (isEnter) {
    if (!customRules.label) return customRulesLabel.value.focus()
    if (!customRules.rule) return customRulesRule.value.focus()
  } else if (!customRules.label || !customRules.rule) return

  form.customRules.push({
    label: customRules.label,
    rule: customRules.rule,
  })
  handleRest()
  if (isEnter) customRulesLabel.value.focus()
}

const handleRest = () => {
  customRules.label = ''
  customRules.rule = ''
}

const open = (data) => {
  fatherData.value = data
  const fatherPerms = data.perms?.split(':') || []
  formDialogRef.value.open("按钮规则生成", {
    rulePrefix: [fatherPerms[0] || '', fatherPerms[1] || ''],
    labelPrefix: data.menuName,
  })
}

const emits = defineEmits(['success'])

const generateBtnRule = async (form) => {
  const prefix = form.rulePrefix.join(':') + ':'
  const allRules = form.rules.concat(form.customRules)
  const params = allRules.map((rule, index) => ({
    icon: undefined,
    frame: false,
    cache: false,
    parentId: fatherData.value.id,
    menuName: form.labelPrefix + rule.label,
    menuType: 'F',
    sort: index,
    perms: prefix + rule.rule,
    path: '',
    visible: '0',
    status: '0'
  }))

  if (params.length === 0) return formDialogRef.value.close('没有定义规则')
  $xl.apis.generateButtonPermission({
    params: params,
    type: 'json'
  }).then(() => {
    formDialogRef.value.close()
    emits('success')
  }).catch(err => formDialogRef.value.close(err))
}

const resetForm = () => {
  fatherData.value = {}
  checked.isIndeterminate = false
  checked.checkAll = false
  customRules.label = ''
  customRules.rule = ''
}

defineExpose({
  open
})
</script>

